package com.jacky.flutter_screen_recording;

import android.os.Handler;
import android.os.Looper;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class CountTimer {

    private Timer mTimer;
    private TimerTask timerTask;
    private int maxTime;

    private long startTime;

    private final Handler mHandler;

    public CountTimer() {
        mHandler = new Handler(Looper.getMainLooper());

        mTimer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                int runTime = (int) ((System.currentTimeMillis() - startTime) / 1000);
                mHandler.post(() -> result(runTime));
                if(runTime >= maxTime) stop();
            }
        };
    }

    public void stop() {
        mTimer.cancel();
        timerTask.cancel();
    }

    public void schedule(int maxTime, int period) {
        this.maxTime = maxTime;
        startTime = System.currentTimeMillis();
        mTimer.scheduleAtFixedRate(timerTask, 0, period * 1000L);
    }

    protected void result(int runTime) {

    }

    public static String getFormat(int duration){
        if(duration >= 3600) return getFormatDuration(duration);
        return getFormatDurationForMinute(duration);
    }

    /**
     * 将指定的秒数转换成00:00格式时间，例如：65转换后为01:05
     */
    public static String getFormatDurationForMinute(int duration) {
        int minute = duration / 60;
        int second = duration % 60;
        return String.format(Locale.CHINESE,"%02d:%02d", minute,second);
    }

    /**
     * 将指定的秒数转换成00:00:00格式时间，例如：65转换后为00:01:05
     */
    public static String getFormatDuration(int duration) {
        int time = duration % 3600;
        int hour = duration / 3600;
        int minute = time / 60;
        int second = time % 60;
        return String.format(Locale.CHINESE,"%02d:%02d:%02d",hour, minute,second);
    }
}
